# Flask middleware - API request logging
from flask import request, session, g
import time
from .logging_config import app_logger

def log_api_requests(app):
    """Flask application middleware: Log API requests"""
    
    @app.before_request
    def before_request():
        g.start_time = time.time()
    
    @app.after_request
    def after_request(response):
        # Calculate response time
        if hasattr(g, 'start_time'):
            response_time = (time.time() - g.start_time) * 1000  # Convert to milliseconds
        else:
            response_time = None
        
        # Get user ID
        user_id = session.get('user_id') if session else None
        
        # Log API request
        app_logger.log_api_request(
            method=request.method,
            endpoint=request.endpoint or request.path,
            user_id=user_id,
            status_code=response.status_code,
            response_time=response_time
        )
        
        return response
    
    @app.errorhandler(Exception)
    def handle_exception(e):
        # Log unhandled exceptions
        user_id = session.get('user_id') if session else None
        
        app_logger.log_error(
            error_type=type(e).__name__,
            error_message=str(e),
            user_id=user_id,
            details={
                'endpoint': request.endpoint or request.path,
                'method': request.method,
                'args': dict(request.args),
                'form': dict(request.form) if request.form else None
            }
        )
        
        # Re-raise exception to let Flask's default error handler handle it
        raise e
